package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gin/models"
	"io"
	"net/http"
	"strconv"
	"time"
)

type JsonData struct {
	Data             dataInfo
	ErrorCode        interface{} `json:"error_code"`
	ErrorDescription interface{} `json:"error_description"`
}

type dataInfo struct {
	Count interface{} `json:"count"`
	List  []list
}

type list struct {
	Symbol string `json:"symbol"`
	Name   string `json:"Name"`
}

type Snowball struct {
	Id   int64
	Code string
}

func main() {
	models.InitDb()
	//codeSaveToDb("ddc")
	for i := 1; i <= 150; i++ {
		getData(i)
	}
}

func codeSaveToDb(code string) {
	snoball := Snowball{}
	snoball.Code = code
	models.Db.Table("snowball").Create(&snoball)
}

func getData(page int) {
	client := &http.Client{Timeout: 5 * time.Second}
	url := "https://xueqiu.com/service/v5/stock/screener/quote/list?page=" + strconv.Itoa(page) + "&size=30&order=desc&orderby=percent&order_by=percent&market=CN&type=sh_sz&_=1626092276754"
	fmt.Println(url)
	resp, err := client.Get(url)
	if err != nil {
		fmt.Println(err)
	}

	defer resp.Body.Close()
	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			fmt.Println(err)
		}
	}

	str := []byte(result.String())
	jsonData := JsonData{}
	err = json.Unmarshal(str, &jsonData)
	if err != nil {
		fmt.Println(err)
	}
	// fmt.Println(jsonData.Data.List)
	for _, v := range jsonData.Data.List {
		fmt.Println(v.Symbol)
		codeSaveToDb(v.Symbol)
	}
}
